<?php

namespace app\controller;

use app\BaseController;
use app\Log;
use app\model\ProductCode;
use hsg\Hsg;
use payment\Hpay;

class Wechat extends BaseController
{
    const appid = "wxefde22e2c4ec1491";
    const appSecret = "e92856075e326e95b71ca179d6ae9895";

    public function access()
    {
        header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . self::appid . "&redirect_uri=" . urlencode("http://admin.zhixingjiuzhou.com/wechat/openid") . "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect");
    }

    public function pay()
    {
        header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . self::appid . "&redirect_uri=" . urlencode("http://admin.zhixingjiuzhou.com/wechat/payment") . "&response_type=code&scope=snsapi_base&state=" . request()->param("id") . "#wechat_redirect");
    }

    public function openid()
    {
        $code = $this->request->param("code");
        //获取access_token及openid
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . self::appid . "&secret=" . self::appSecret . "&code=" . $code . "&grant_type=authorization_code";
        $data = json_decode(file_get_contents($url), true);
        if (empty($data) || empty($data['openid'])) {
            header("location:http://zhixingjiuzhou.com");
            exit;
        }
        header("location:http://zhixingjiuzhou.com/?openid=" . $data['openid']);
    }

    public function payment()
    {
        $code = $this->request->param("code");
        //获取access_token及openid
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . self::appid . "&secret=" . self::appSecret . "&code=" . $code . "&grant_type=authorization_code";
        $data = json_decode(file_get_contents($url), true);
        if (empty($data) || empty($data['openid'])) {
            header("location:http://zhixingjiuzhou.com/pages/payment/payment?id=" . $this->request->param("state"));
            exit;
        }
        header("location:http://zhixingjiuzhou.com/pages/payment/payment?id=" . $this->request->param("state") . "&openid=" . $data['openid']);
    }

    public function pay_notify()
    {
        $params = $this->request->param();
        $log = new Log("wechat/notify");
        //校验签名
        if ($this->app->make(Hpay::class)->setSign($params) != $params['sign']) {
            $log->write(['params' => $params, 'message' => "签名验证失败！"], "error");
            return json_encode(["code" => "ERROR", "message" => "签名验证失败！"], 320);
        }
        $order = $this->app->make(\app\model\Order::class);
        $state = 2;
        if ($params['status'] > 3) {
            $state = 4;
        } else if ($params['status'] != 3) {
            $state = 1;
        }
        $order->where(['order_sn' => $params['outTradeNo']])->update(['state' => $state, 'pay_sn' => $params['accTradeNo'], 'pay_time' => date("Y-m-d H:i:s")]);
        //处理业务逻辑
        if ($params['status'] == 3) {
            $_order = $order->with(['productData'])->where(['order_sn' => $params['outTradeNo']])->select()->toArray();
            if (!empty($_order)) {
                $coupon = $this->app->make(ProductCode::class);
                foreach ($_order as $v) {
                    $pro = $v['productData'];
                    if ($pro['type'] == 4) {
                        //券码，查询券码库存是否充足
                        $values = $coupon->where(['pid' => $pro['id'], 'state' => 1, 'is_del' => 1,])->limit($v['number'])->column("id");
                        if (count($values) == $v['number']) {
                            $order->where(['id' => $v['id']])->update(['state' => 5]);//券码生成成功
                            $coupon->where(['id' => $values])->update(['state' => 2, 'draw_time' => date("Y-m-d H:i:s")]);
                        } else {
                            $order->where(['id' => $v['id']])->update(['state' => 6]);//券码生成失败
                        }
                    } else if ($pro['type'] == 1) {
                        //虚拟卡券
                        $code = explode("-", $pro['bar_code']);
                        if ($code[0] == 'HSG') {
                            $hsg = new Hsg;
                            $createCoupon = $hsg->createFindCoupon($v['account'], end($code), $v['number']);
                            if ($createCoupon['code'] != 0) {
                                $order->where(['id' => $v['id']])->update(['state' => 6]);//发券失败
                            } else {
                                $its = $createCoupon['data'];
                                $url = $hsg->createUrl($v['account']);
                                $its['url'] = $url;
                                $order->where(['id' => $v['id']])->update(['state' => 5, 'order_info' => json_encode($its, 320)]);//发券成功
                            }
                        }
                    } else if ($pro['type'] == 3) {
                        $order->where(['id' => $v['id']])->update(['state' => 5, 'order_info' => json_encode(['url' => $pro['user_text']])]);//发券成功
                    } else {
                        $order->where(['id' => $v['id']])->update(['state' => 5]);//发券成功
                    }
                }
            }
        }
        return json_encode(["code" => "SUCCESS", "message" => "订单处理成功！"], 320);
    }
}